package de.slothsoft.wasbinich.android;

import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import de.slothsoft.wasbinich.android.util.ActivityUtil;
import de.slothsoft.wasbinich.android.util.MediaPlayerUtil;
import de.slothsoft.wasbinich.android.util.SvgUtil;

public abstract class AbstractActivity extends Activity {

    public static class CallBack implements Cloneable {

	public void onCreate(AbstractActivity activity) {
	    // nothing to do on default
	}

	public void onPause(AbstractActivity activity) {
	    // nothing to do on default
	}

	public void onResume(AbstractActivity activity) {
	    // nothing to do on default
	}

	public void onDestroy(AbstractActivity activity) {
	    // nothing to do on default
	}

	@Override
	public CallBack clone() {
	    try {
		return (CallBack) super.clone();
	    } catch (CloneNotSupportedException e) {
		throw new InternalError(e.getMessage());
	    }
	}
    }

    public static CallBack ACTIVITY_CALL_BACK = new CallBack();

    protected CallBack activityCallBack = ACTIVITY_CALL_BACK.clone();

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
	super.onWindowFocusChanged(hasFocus);
	View view = getWindow().getDecorView();
	SvgUtil.setSvgToBackground(this, view, R.raw.background);
	ActivityUtil.setCurrentActivity(this);
	setVolumeControlStream(AudioManager.STREAM_MUSIC);
	super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	ActivityUtil.addActivity(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	case android.R.id.home:
	    NavUtils.navigateUpFromSameTask(this);
	    return true;
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    public void setContentView(int layoutResID) {
	super.setContentView(layoutResID);
	this.activityCallBack.onCreate(this);
    }

    public View getLayoutView() {
	return findViewById(R.id.layout);
    }

    @Override
    protected void onResume() {
	this.activityCallBack.onResume(this);
	super.onResume();
	MediaPlayerUtil.startMusic(this);
    }

    @Override
    protected void onPause() {
	MediaPlayerUtil.stopMusic();
	this.activityCallBack.onPause(this);
	super.onPause();
    }

    @Override
    protected void onDestroy() {
	this.activityCallBack.onDestroy(this);
	ActivityUtil.removeActivity(this);
	super.onDestroy();
    }

    protected void handleException(final Exception exception) {
	ActivityUtil.handleException(this, exception);
    }

    protected void handleFatalException(final Exception exception) {
	ActivityUtil.handleFatalException(this, exception);
    }
}
